package com.chookss.home.logContacts;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.ContactEntity;
import com.chookss.mine.personal.PersonalHomeActivity;
import com.chookss.tiku.view.FlowLayout;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.CircleImageView;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import scut.carson_ho.searchview.EditText_Clear;

//单纯通讯录
public class ContactsActivity extends BaseAct {
    @BindView(R.id.statusBar)
    View statusBar;
    @BindView(R.id.title_back)
    LinearLayout title_back;
    @BindView(R.id.et_search)
    EditText_Clear etSearch;
    @BindView(R.id.tvCompany)
    TextView tvCompany;
    @BindView(R.id.rvView)
    RecyclerView rvView;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;
    @BindView(R.id.llSearchEmpty)
    LinearLayout llSearchEmpty;
    @BindView(R.id.ivSearchEmpty)
    ImageView ivSearchEmpty;
    @BindView(R.id.tvSearchEmpty)
    TextView tvSearchEmpty;
    @BindView(R.id.tv2SearchEmpty)
    TextView tv2SearchEmpty;
    @BindView(R.id.rlSearch)
    RelativeLayout rlSearch;
    @BindView(R.id.flowLayout)
    FlowLayout flowLayout;
    private String key = "", companyNmae = "", oldCompanyNmae = "";//关键字、组织名、部门
    private ContactsAdapter adapter;
    private List<ContactEntity> list = new ArrayList<>();
    private String orgCode = "";
    private int currentPage = 1;
    private boolean isEnd = false;//是否到底
    private ArrayList<String> nameList = new ArrayList<>();//组织及部门排列
    private FlowAdapter nameAdapter;
    private List<ContactEntity> selectList = new ArrayList<>();
    private String phoneFlag="1";//0禁止通话1正常
    private String lpFlag = "";//0禁止1正常
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);
        ButterKnife.bind(this);
        NavigationTools.saveUseRecord(this,"1","07");
        lpFlag = new ShareUtils().getString(this, StaticClass.LP_FLAG, "1");
        //禁止截屏
        if ("0".equals(lpFlag)) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        }
        phoneFlag=new ShareUtils().getString(this,StaticClass.PHONE_FLAG,"1");
        orgCode = getIntent().getStringExtra("orgCode");
        key = getIntent().getStringExtra("key");
        companyNmae = getIntent().getStringExtra("companyNmae");
        oldCompanyNmae = getIntent().getStringExtra("oldCompanyNmae");
        ArrayList<String> nameLists = getIntent().getStringArrayListExtra("nameList");
        if (nameLists != null) {
            nameList.addAll(nameLists);
            nameList.add(oldCompanyNmae);
        }
        NavigationTools.setWaterMark(this, "15");
    }

    @Override
    public void initData() {
        initState();
        statusBar.setVisibility(View.GONE);
        title_back.setVisibility(View.VISIBLE);
        if (nameList.size() > 0) {
            flowLayout.setVisibility(View.VISIBLE);
            tvCompany.setVisibility(View.GONE);
            nameAdapter = new FlowAdapter(this, nameList);
            flowLayout.setAdapter(nameAdapter);
        } else {
            companyNmae = new ShareUtils().getString(this, StaticClass.COMPANYNAME, "");
            if (Utils.isNull(companyNmae)) {
                companyNmae = getResources().getString(R.string.app_name);
            }
            nameList.add(companyNmae);
            flowLayout.setVisibility(View.GONE);
            tvCompany.setVisibility(View.VISIBLE);
            tvCompany.setText(companyNmae);
        }
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {   // 按下完成按钮，这里和上面imeOptions对应
                    if (!Utils.isNull(v.getText().toString())) {
                        key = v.getText().toString();
                        etSearch.setText(key);
                        tvCompany.setText(companyNmae);
                        tvCompany.setVisibility(View.VISIBLE);
                        flowLayout.setVisibility(View.GONE);
                        isEnd = false;
                        currentPage = 1;
                        showLoading();
                        getData();
                        return false;   //返回true，保留软键盘。false，隐藏软键盘
                    } else {
                        MyToast.show("请输入关键词");
                    }
                }
                return true;   //返回true，保留软键盘。false，隐藏软键盘
            }
        });

        rvView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new ContactsAdapter(R.layout.item_contacts, list);
        rvView.setAdapter(adapter);
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        srlView.setEnableRefresh(false);
        showLoading();
        getData();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        String url = "";
        if (Utils.isNull(key)) {
            map.put("orgCode", orgCode);
            url = Urls.selectOrgAndEmpByCode;
        } else {
            map.put("searchParam", key);
            url = Urls.selectEmpByParam;
        }
        map.put("pageNum", currentPage + "");
        map.put("pageSize", "20");
//        if(Utils.isNull(source)){
//            //不需要权限，可以查看所有人
//            map.put("type", "0");
//        }else{
        //需要权限，只能查看下属的
        map.put("type", "1");
//        }

        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ContactEntity>>>() {
        }.getType(), null, url, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<ContactEntity>>() {
            @Override
            public void onSuccess(List<ContactEntity> data) {
                dismissLoading();
                loadEnd();
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (llSearchEmpty == null||rvView==null) {
                    return;
                }
                if (data.size() == 0) {
                    isEnd = true;
                    if (list.size() == 0) {
                        rvView.setVisibility(View.GONE);
                        llSearchEmpty.setVisibility(View.VISIBLE);
                    }
                } else {
                    list.addAll(data);
                    rvView.setVisibility(View.VISIBLE);
                    llSearchEmpty.setVisibility(View.GONE);
                    adapter.notifyDataSetChanged();
                }

            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    class ContactsAdapter extends BaseQuickAdapter<ContactEntity, BaseViewHolderEx> {

        public ContactsAdapter(int layoutResId, List<ContactEntity> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolderEx helper, ContactEntity entity) {
            //组织
            LinearLayout llCompany = helper.getView(R.id.llCompany);
            TextView tvContactsName = helper.getView(R.id.tvContactsName);
            TextView tvContactsNum = helper.getView(R.id.tvContactsNum);
            //员工
            LinearLayout llEmployees = helper.getView(R.id.llEmployees);
            CircleImageView ivEmployees = helper.getView(R.id.ivEmployees);
            ImageView tvEmployeesPhone = helper.getView(R.id.tvEmployeesPhone);
            TextView tvEmployeesName = helper.getView(R.id.tvEmployeesName);
            TextView tvEmployeesJob = helper.getView(R.id.tvEmployeesJob);
            if("0".equals(phoneFlag)){
                tvEmployeesPhone.setAlpha(0.3f);
            }
            if ("0".equals(entity.getType())) {
                //部门
                llCompany.setVisibility(View.VISIBLE);
                llEmployees.setVisibility(View.GONE);
                tvContactsName.setText(entity.getEmployeeName());
                tvContactsNum.setText("(" + entity.getEmpNum() + ")");
            } else {
                //员工
                llCompany.setVisibility(View.GONE);
                llEmployees.setVisibility(View.VISIBLE);
                GlideUtils.loadAvatar(ContactsActivity.this, entity.getHeadPhotoThumbUrl(), ivEmployees);

                if (Utils.isNull(key)) {
                    tvEmployeesName.setText(entity.getEmployeeName());
                } else {
                    tvEmployeesName.setText(Utils.matcherSearchTitle(getResources().getColor(R.color.main_color), entity.getEmployeeName(), key));
                }
                tvEmployeesJob.setText(entity.getPost());
            }
            tvEmployeesPhone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    if("1".equals(phoneFlag)){
                        toPhone(entity.getPhone());
                    }else{
                        MyToast.show("管理员已禁用拨打电话功能");
                    }
                }
            });
            ivEmployees.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    Intent intent = new Intent(ContactsActivity.this, PersonalHomeActivity.class);
                    intent.putExtra("employeeCode", entity.getEmployeeCode());
                    startActivity(intent);

                }
            });
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    if ("0".equals(entity.getType())) {
                        //是组织
                        Intent intent = new Intent(ContactsActivity.this, ContactsActivity.class);
                        intent.putExtra("orgCode", entity.getEmployeeCode());
                        intent.putExtra("companyNmae", companyNmae);
                        intent.putExtra("oldCompanyNmae", entity.getEmployeeName());
                        intent.putStringArrayListExtra("nameList", nameList);
                        intent.putExtra("department", entity.getEmployeeName());
                        startActivity(intent);
                    }
                }
            });
        }
    }


    @OnClick({R.id.title_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
        }
    }

    class FlowAdapter extends FlowLayout.Adapter<FlowAdapter.FlowViewHolder> {

        private static final String TAG = "FlowAdapter";

        private Context mContext;
        private List<String> mContentList;

        public FlowAdapter(Context mContext, List<String> mContentList) {
            this.mContext = mContext;
            this.mContentList = mContentList;
        }

        @Override
        public FlowAdapter.FlowViewHolder onCreateViewHolder(ViewGroup parent) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_contacts_name_list, parent, false);

            return new FlowAdapter.FlowViewHolder(view);
        }

        @Override
        public void onBindViewHolder(FlowAdapter.FlowViewHolder holder, int position) {
            holder.tvTitle.setText(mContentList.get(position));
            if (position == 0) {
                holder.ivArrow.setVisibility(View.GONE);
                holder.tvTitle.setTextColor(Color.parseColor("#818080"));
            } else {
                holder.ivArrow.setVisibility(View.VISIBLE);
                holder.tvTitle.setTextColor(Color.parseColor("#333333"));
            }
        }

        @Override
        public int getItemCount() {
            return mContentList.size();
        }

        class FlowViewHolder extends FlowLayout.ViewHolder {
            TextView tvTitle;
            ImageView ivArrow;

            public FlowViewHolder(View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tvTitle);
                ivArrow = itemView.findViewById(R.id.ivArrow);
            }
        }
    }

    private void toPhone(String phone) {
        if (!Utils.isNull(phone)) {
            XXPermissions.with((Activity) this)
                    .permission(Permission.CALL_PHONE)
                    .request(new OnPermissionCallback() {

                        @Override
                        public void onGranted(List<String> granted, boolean all) {
                            if (all) {
                                Intent callIntent = new Intent(Intent.ACTION_CALL,
                                        Uri.parse("tel:" + phone.replace("-", "")));
                                if (ActivityCompat.checkSelfPermission(ContactsActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                    return;
                                }
                                startActivity(callIntent);
                            } else {
                                PermissionUtils.errorSinglePermission(granted);
                            }
                        }

                        @Override
                        public void onDenied(List<String> denied, boolean quick) {
                            PermissionUtils.errorPermission(ContactsActivity.this, denied, quick);
                        }
                    });
        }
    }

    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh(true);
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore(true);
    }

}
